<script setup lang="ts">

import {computed, onBeforeMount, ref, watch, type CSSProperties} from "vue";
import {type FormInst, type SelectOption, type FormItemRule, useMessage} from "naive-ui";
import CustomModal from "@components/CustomModal/index.ts";
import {getRequest, postOrputRequest, putRequest} from "@/api";

import {appThemeColors, emails_suffix} from '@/config'

interface AdminItem {
  id: number
  account: string | null
  password: string | null
  nickname: string | null
  phone: string | null
  email: string | null
  is_locked: 0 | 1
  role: number | null
}

const message = useMessage()

const visible = defineModel('visible', {type: Boolean, default: false});
const props = defineProps<{
  formData?: Recordable;
}>();
const emits = defineEmits(["closeModal"])

const roleOptions = ref<SelectOption[]>([])

const handelSubmitLoading = ref<boolean>(false)
const formRef = ref<FormInst | null>(null)
const addEditForm = ref<AdminItem>({
  id: 0,
  account: null,
  password: null,
  nickname: null,
  phone: null,
  email: null,
  is_locked: 0,
  role: null,
})
// 默认表单值，用于重置
const defaultFormValues: AdminItem = {
  id: 0,
  account: null,
  password: null,
  nickname: null,
  phone: null,
  email: null,
  is_locked: 0,
  role: null,
}
const addEditFormRules = computed(() => {
  return {
    role: {
      type: 'number',
      required: true,
      trigger: ['change', 'blur'],
      message: '请选择所属角色',
    },
    nickname: {
      required: true,
      trigger: ['input', 'blur'],
      message: '请输入管理员昵称'
    },
    account: {
      required: true,
      trigger: ['blur'],
      asyncValidator: (_rule: FormItemRule, value: string) => {
        return new Promise<void>((resolve, reject) => {
          const regex = /^[A-Za-z0-9]+$/;
          if (!value) {
            reject(Error('请输入管理员登录账号'))
          } else if (!regex.test(value)) {
            reject(Error('管理员账号只能是英文加数字')) // reject with error message
          } else if (value.length < 3 || value.length > 12) {
            reject(Error('请输入长度为3~12的管理员登录账号'))
          } else {
            putRequest('/admins/check_account', {
              id: addEditForm.value.id,
              account: addEditForm.value.account
            },0).then((result) => {
              if(result.data){
                resolve()
              }else {
                reject(Error(result.message))
              }
            })
          }
        })
      }
    },
    password: {
      required: !addEditForm.value.id,
      trigger: ['input', 'blur'],
      validator: (_rule: FormItemRule, value: string) => {
        return new Promise<void>((resolve, reject) => {
          if (!value && !addEditForm.value.id) {
            reject(Error("请输入登录密码"));
          } else if (value && value.length < 6) {
            reject(Error("请输入6位或6位以上的登录密码"));
          } else {
            resolve();
          }
        });
      },
    },
    is_locked: {
      type: 'number',
      required: true,
      trigger: ['change'],
    }
  }
})
const emailOptions = computed(() => {
  return emails_suffix.map((suffix) => {
    if (addEditForm.value.email) {
      const prefix = addEditForm.value.email.split("@")[0];
      return {
        label: prefix + suffix,
        value: prefix + suffix,
      };
    }
  });
});

const railStyle = ({checked}: { checked: boolean }) => {
  const style: CSSProperties = {}
  if (!checked) {
    style.background = appThemeColors.errorColor
  }
  return style
}

//提交数据
const confirmBtn = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      handelSubmitLoading.value = true;
      postOrputRequest('/admins/save', addEditForm.value).then((res: ResponseResult) => {
        if (res.code === 200) {
          message.success(res.message, {
            duration: 1500,
            onLeave() {
              visible.value = false
              emits('closeModal', addEditForm.value.id ? 2 : 1)
            }
          })
        } else {
          message.error(res.message);
          handelSubmitLoading.value = false;
        }
      })
    }
  })
}
// 关闭模态框
const closeModal = () => {
  // 使用Object.assign快速重置表单
  Object.assign(addEditForm.value, defaultFormValues)
  handelSubmitLoading.value = false
}

watch(() => props.formData, (newValue) => {
  if (newValue && Object.keys(newValue).length > 0) {
    Object.assign(addEditForm.value, {
      ...defaultFormValues,
      ...newValue
    })
  }
}, {immediate: true, deep: true})

//获取角色
const getRoleOptions = async () => {
  await getRequest('/role/get_role').then(res => {
    roleOptions.value = res.data as SelectOption[];
  })
}
onBeforeMount(() => {
  getRoleOptions();
})
</script>

<template>
  <custom-modal v-model:show="visible"
                :widths="680"
                :handel-submit-loading="handelSubmitLoading"
                @confirm="confirmBtn"
                @after-leave="closeModal"
                confirmText="确认"
                :title="`${addEditForm.id?'编辑':'新增'}管理员`">
    <template #default>
      <n-form ref="formRef"
              :model="addEditForm"
              :rules="addEditFormRules"
              require-mark-placement="left"
              :label-width="55"
              label-placement="left">
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="角色" path="role">
            <n-select v-model:value="addEditForm.role" :options="roleOptions" placeholder="请选择所属角色" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="昵称" path="nickname">
            <n-input v-model:value="addEditForm.nickname" placeholder="请输入昵称" clearable/>
          </n-form-item-gi>
        </n-grid>

        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="账号" path="account">
            <n-input v-model:value="addEditForm.account" placeholder="请输入账号(登录账号)" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="密码" path="password">
            <n-input v-model:value="addEditForm.password" placeholder="请输入登录密码" clearable/>
          </n-form-item-gi>
        </n-grid>

        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="电话" path="phone">
            <n-input v-model:value="addEditForm.phone" placeholder="请输入管理员电话" maxlength="11" clearable/>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="邮箱" path="email">
            <n-auto-complete v-model:value="addEditForm.email" :options="emailOptions"
                             placeholder="请输入管理员电子邮箱"
                             clearable/>
          </n-form-item-gi>
        </n-grid>
        <n-form-item label="状态" path="is_locked" :show-feedback="false">
          <n-switch v-model:value="addEditForm.is_locked" :round="false" :checked-value="0" :unchecked-value="1"
                    :rail-style="railStyle">
            <template #checked>
              正常
            </template>
            <template #unchecked>
              锁定
            </template>
          </n-switch>
        </n-form-item>
      </n-form>
    </template>
  </custom-modal>
</template>

<style scoped lang="scss">

</style>